﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using Chire.ChireInter.Students;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Chire.ChireInter.Wechat;
using Chire.ChireInter.Parent;
using Chire.ChireInter.Class;

namespace Chire.ChireInter.Sign
{
    /// <summary>
    /// Sign_Status 的摘要说明
    /// </summary>
    public class Sign_Status : IHttpHandler
    {
        HttpContext contextWithBase;
        string code = "";
        string openid = "";                 // 微信获取到的微信id
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            contextWithBase = context;
            analysisInfo();
        }

        #region 验证信息
        public void analysisInfo()
        {
            if (contextWithBase.Request.Form.AllKeys.Contains("openid"))
            {
                openid = contextWithBase.Request.Form["openid"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("code"))
            {
                code = contextWithBase.Request.Form["code"];
            }

            
            if (openid.Length <= 0)
            {
                openid = getOpenIdWithCode();
            }
            actionManager();

        }
        #endregion

        #region 执行操作
        public void actionManager()
        {
            Student_Action studentAction = new Student_Action();
            Student_Model studentModel = new Student_Model();
            Student_Model tempStudentModel = studentAction.getStudentInfoWithStudentOpenId(openid);
            bool hasParent = false;
            // 1. 判断是否是学生
            if (tempStudentModel.id != null)                // 表示有学生
            {
                studentModel = tempStudentModel;
            }
            else {
                Parent_Action parentAction = new Parent_Action();
                Student_Model parentStudentModel = parentAction.getStudentIdWithBindingParentId(openid);
                if (parentStudentModel.id != null) {
                    studentModel = parentStudentModel;
                    hasParent = true;
                }
            }

            if (studentModel.id != null)                // 表示有学生
            {
                Sign_Status_Model signStatusModel = new Sign_Status_Model();
                Class_Action classAction = new Class_Action();

                Sign_Model inModel = hasSignInToday(studentModel.id, studentModel.classid);
                Sign_Model outModel = hasSignOutToday(studentModel.id, studentModel.classid);
                signStatusModel.sign_in = inModel;
                signStatusModel.sign_out = outModel;
                signStatusModel.classModel = classAction.getClassInfoWithId(studentModel.classid);

                if (inModel.id != null && outModel.id != null)
                {
                    if (hasParent == true)
                    {            // 表示是家长
                        statusSuccessManager(signStatusModel, "201");
                    }
                    else {
                        statusSuccessManager(signStatusModel,"200");
                    }
                }
                else {
                    successManager("503", "今日无课，或联系授课老师进行设置");

                }
            }
            else
            {
                successManager("401", "请先去填写学生卡,或者绑定学员");
            }
        }
        #endregion

        #region 去判断今天是否有签到过
        public Sign_Model hasSignInToday(string student_id, string class_id)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();

            string strselect = "select top 1 * from [sign] where student_id = '" + student_id + "' and class_id = '" + class_id + "'  and [date] = '" + dateNow + "'";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Sign_Model signModel = new Sign_Model();
            if (dr.Read())
            {
                if (dr["sign_type"].ToString().Equals("1"))
                {
                    signModel.id = dr["id"].ToString();
                    signModel.student_id = student_id;
                    signModel.class_id = class_id;
                    signModel.sign_type = dr["sign_type"].ToString();
                    signModel.date = dr["date"].ToString();
                    signModel.time = dr["time"].ToString();
                }
                else {
                    signModel.id = "";
                    signModel.student_id = "";
                    signModel.class_id = ""; ;
                    signModel.sign_type = "";
                    signModel.date = "";
                    signModel.time = "";
                }
               
            }
            sqlcon.Close();
            return signModel;
        }
        #endregion

        #region 去判断今天是否有签退
        public Sign_Model hasSignOutToday(string student_id, string class_id)
        {
            SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ConnectionString);
            sqlcon.Open();

            string dateNow = DateTime.Now.ToShortDateString().ToString();

            string strselect = "select top 1 * from [sign] where student_id = '" + student_id + "' and class_id = '" + class_id + "' and [date] = '" + dateNow + "'  order by id desc";
            SqlCommand sqlcmd = new SqlCommand(strselect, sqlcon);
            SqlDataReader dr = sqlcmd.ExecuteReader();
            Sign_Model signModel = new Sign_Model();
            if (dr.Read())
            {
                if (dr["sign_type"].ToString().Equals("3"))
                {
                    signModel.id = dr["id"].ToString();
                    signModel.student_id = student_id;
                    signModel.class_id = class_id;
                    signModel.sign_type = dr["sign_type"].ToString();
                    signModel.date = dr["date"].ToString();
                    signModel.time = dr["time"].ToString();
                }
                else
                {
                    signModel.id = "";
                    signModel.student_id = "";
                    signModel.class_id = ""; ;
                    signModel.sign_type = "";
                    signModel.date = "";
                    signModel.time = "";
                }
               
            }
            sqlcon.Close();
            return signModel;
        }
        #endregion

        #region 根据code 获取openid
        public string getOpenIdWithCode()
        {
            Wechat_Action wechatAction = new Wechat_Action();
            string openid = wechatAction.getOpenIdWithCode(code);

            return openid;
        }
        #endregion


        #region 成功方法
        public void successManager(string errcode, string error)
        {

            OUTSign_Model out_base_setting = new OUTSign_Model();
            out_base_setting.errCode = errcode;
            out_base_setting.errMsg = error;
            out_base_setting.data = null;

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }

     
        public void statusSuccessManager(Sign_Status_Model statusModel,string code)
        {

            OUTSign_Status_Model out_base_setting = new OUTSign_Status_Model();
            out_base_setting.errCode = code;
            out_base_setting.errMsg ="接口请求成功";
            out_base_setting.data = statusModel;

            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }
      
        #endregion

        #region 其他
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion
       
    }
}